/**
 * Created by Administrator on 2016/3/7.
 */
(function($) {
    //var arr;
    $.fn.inputChange = function (arr) {

        $(this).click(function() {
            //先拼接字符串
            var str = $(this).val();
            var obj = "#" + $(this).attr("id");
            if (str == "" || str == null || str == undefined) {
                //全查询
                getCandidate(obj, arr,str);
            } else {
                //关键字查询
                getCandidate(obj, arr,str);
            }
            var inputWidth = $(this).width() + 24;
            $(obj).siblings(".input-candidate").width(inputWidth).show().find("li");
        });

        $(this).keyup(function() {
            getCandidate("#" + $(this).attr("id"),arr,$(this).val());
            var inputWidth = $(this).width() + 24;
            $(this).siblings(".input-candidate").width(inputWidth).show().find("li");
        });

        $(this).blur(function() {
            $(this).siblings(".input-candidate").hide();
        });

        //获取所有候选，拼接字符串
        function getCandidate(obj, data,searchStr) {
            var str = "<ul class='input-candidate'>";
            for (var i = 0; i < data.length; i++) {
                if(searchStr == "" || data[i].val.indexOf(searchStr) != -1) {
                    str += "<li><p>" + data[i].val+ "</p></li>";
                }
            }
            str += "</ul>";
            $(obj).siblings(".input-candidate").remove();
            $(obj).parent().append(str).find("li").unbind().on("mousedown", function() {
                $(obj).val($(this).find("p").html());
            });
        }
    }
})(jQuery);